package contegor.scire.core;

/**
 * {@link Concept} implementation.
 * 
 * @version $Revision: 1.3 $ 
 * @author  Héctor Cirbián Pousa ($Author: hector $)
 */
@Version("$Id: ConceptImpl.java,v 1.3 2010-02-01 10:55:38 hector Exp $")
public class ConceptImpl extends ConnectableImpl implements Concept, Cloneable, Comparable<Identifiable> {
  private static final long serialVersionUID = 7029268515055972921L;

  protected IdFragment idFragment;
  protected Id id;
  /** Must be reset after a serialization */
  protected transient Container container;


  /** Package private constructor so this object can't be instantiated outside it. */
  protected ConceptImpl(long creationTime, TransactionId transactionId, IdFragment idFragment) {
    super(creationTime, transactionId);
    this.idFragment = idFragment;
    this.id         = null;
    this.container  = null;
  }

  public IdFragment getLocalIdFragment() {
    return this.idFragment;
  }
  
  public Id getId() {
    if (this.id == null) {
      if (this.container != null)
        this.id = new Id(this.container.getId(), this.idFragment);
      else
        this.id = new Id(this.idFragment);
    }
    return this.id;
  }
    
  public void setContainer(Container container) throws IllegalArgumentException {
    if (this.container != null)
      throw new IllegalArgumentException("Method called more than once.");
    this.container = container;
  }

  /* (non-Javadoc)
   * @see contegor.scire.core.ConnectableImpl#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object rhs) {
    if (this == rhs)
      return true;
    if ((rhs == null) || !(rhs instanceof Concept))
      return false;
    return this.getId().equals(((Concept)rhs).getId());
  }

  /* (non-Javadoc)
   * @see contegor.scire.core.ConnectableImpl#hashCode()
   */
  @Override
  public int hashCode() {
    return this.getId().hashCode();
  }

  public ConceptImpl clone() throws CloneNotSupportedException {
    ConceptImpl aux = (ConceptImpl)super.clone();
    aux.container = null;
    return aux;
    // Id and IdFragment are immutable, so there is no need to clone them.
    // The Container must never be cloned.
  }

  @Override
  public int compareTo(Identifiable rhs) {
    return this.getId().compareTo(rhs.getId());
  }

  @Override
  public String toString() {
    return "ConceptImpl [id=" + id + ", idFragment=" + idFragment + "] " + super.toString();
  }
}